package com.hui10.mediaplayer.base

import android.graphics.Color
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import com.hui10.mediaplayer.R
import kotlinx.android.synthetic.main.fragment_home.*

/**
 * Author: Created by lucus on 2019/5/30.
 * E-mail: mcphilex1989@gmail.com
 * Tel: 15652608401
 */
abstract class BaseListFragment<RESPONSE, ITEMBEAN, ITEMVIEW : View> : BaseFragment(),
    BaseView<RESPONSE> {

    val presenter by lazy { getSpecialPresenter(this) }


    private val adapter by lazy { getSpecialAdapter() }


    override fun initView(): View? = View.inflate(context, R.layout.fragment_home, null)

    override fun initListener() {
        super.initListener()
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = adapter

        refreshLayout.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN)
        refreshLayout.setOnRefreshListener {
            presenter.loadData(BasePresenter.DATA_INIT_OR_REFRESH)
        }

        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    val layoutManager = recyclerView.layoutManager
                    if (layoutManager is LinearLayoutManager) {
                        val layoutManager: LinearLayoutManager = layoutManager
                        // 最后一条已经显示
                        val findLastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
                        if (findLastVisibleItemPosition == adapter.itemCount - 1) {
                            presenter.loadMoreData(BasePresenter.DATA_LOAD_MORE, adapter.itemCount - 1)
                        }
                    }
                }
            }
        })
    }

    override fun initData() {
        super.initData()
        presenter.loadData(BasePresenter.DATA_INIT_OR_REFRESH)
    }

    override fun onError(type: Int, message: String?) {
        refreshLayout.isRefreshing = false
        showT(message!!)
    }

    override fun onSuccess(type: Int, response: RESPONSE?) {
        refreshLayout.isRefreshing = false
        adapter.notifyDataChanged(type, getList(response))
    }

    abstract fun getSpecialAdapter(): BaseListAdapter<ITEMBEAN, ITEMVIEW>

    abstract fun getSpecialPresenter(baseView: BaseView<RESPONSE>): BasePresenter<RESPONSE>

    abstract fun getList(response: RESPONSE?): List<ITEMBEAN>?

    override fun onDestroyView() {
        super.onDestroyView()
        presenter.onDestroyView()
    }
}